
const id = window.localStorage.getItem('id')
console.log(id)
const token = window.localStorage.getItem('token')

// 获取元素
const idInp = document.querySelector('.id')
const nickInp = document.querySelector('.main > .form > label > .nickname')
const ageInp = document.querySelector('.main > .form > label > .age')
const genderInp = document.querySelector('.main > .form > label > .gender')
const form = document.querySelector('form')

// 判断
if (!id) window.location.href = './login.html'

// 2. 请求当前用户的个人信息
ajax({
    url: 'http://localhost:8888/users/info',
    data: { id },
    headers: { authorization: token },
    dataType: 'json',
    success(res) {
        // 判断, 登录状态过期了
        if (res.code === 401) {
            // 直接跳转回到登录页
            window.location.href = './login.html'
            return
        }

        if (res.code === 1) {
            // 拿到用户信息了, 填写到表单上
            idInp.value = res.info.id
            ageInp.value = res.info.age
            genderInp.value = res.info.gender
            nickInp.value = res.info.nickname
        }
    }
})

// 3. 点击按钮确认修改
form.addEventListener('submit', e => {
    e.preventDefault()

    // 采集信息
    const info = { id }
    if (nickInp.value) info.nickname = nickInp.value
    if (ageInp.value) info.age = ageInp.value
    if (genderInp.value) info.gender = genderInp.value

    // 发送请求
    ajax({
        url: 'http://localhost:8888/users/update',
        method: 'POST',
        data: info,
        headers: { authorization: token },
        dataType: 'json',
        success(res) {
            if (res.code === 1) {
                alert('修改用户信息成功')
            }
        }
    })
})
